package com.ecsolutions.controller;

import com.ecsolutions.Validators.Tbluser_role_Validate;
import com.ecsolutions.Validators.User_Validate;
import com.ecsolutions.entity.Tbluser_role_Entity;
import com.ecsolutions.entity.User_Entity;
import com.ecsolutions.service.Tbluser_Properties_Service;
import com.ecsolutions.service.User_Service;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


/**
 * Created by ecs on 2017/8/18.
 */
@Controller
public class User_Controller {
//    private String user;

    @Autowired
    private User_Service user_service;

    @Autowired
    private Tbluser_Properties_Service tbluser_properties_service;

    public Tbluser_Properties_Service getTbluser_properties_service() {
        return tbluser_properties_service;
    }

    public User_Service getUser_service() {
        return user_service;
    }

    @InitBinder("user_entity")
    public void initUserBinder(WebDataBinder binder) {
        binder.setValidator(new User_Validate());
    }

    @InitBinder("role_entity")
    public void initRoleBinder(WebDataBinder binder) {
        binder.setValidator(new Tbluser_role_Validate());
    }

    @GetMapping("/User")
    public String getUser(Model model) {
        model.addAttribute("user_entity", new User_Entity());
        model.addAttribute("BranchCodeList", user_service.getBranchCodeList());
        model.addAttribute("RoleInfoList", user_service.getRoleInfoList());
        model.addAttribute("role_entity", new Tbluser_role_Entity());
        return "ClientInformation/User";
    }

    @PostMapping("/User")
    public String postUser(Model model, @Valid @ModelAttribute("user_entity") User_Entity user_entity, BindingResult result1,
                           @Valid @ModelAttribute("role_entity") Tbluser_role_Entity role_entity, BindingResult result2) {
        model.addAttribute("user_entity", user_entity);
        model.addAttribute("BranchCodeList", user_service.getBranchCodeList());
        model.addAttribute("RoleInfoList", user_service.getRoleInfoList());
        model.addAttribute("role_entity", role_entity);
        if (!result1.hasErrors()) {
            if (user_service.findOne(user_entity.getUserid())) {
                user_service.update(user_entity);
            } else {
                user_service.save(user_entity);
                tbluser_properties_service.initNewUserProperty(user_entity.getUserid());
            }
        }
        if (!result2.hasErrors()) {
            if (null != user_entity.getRoleid()) {
                String[] userRoleIdListString = user_entity.getRoleid().split(",");
                List<String> userRoleIdOldList = Arrays.asList(userRoleIdListString);
                List<String> userRoleIdList = new ArrayList(userRoleIdOldList);
                List<String> SqlList = user_service.getUserRoleInfoList(user_entity.getUserid());
                //去除相同元素
                for (int i = 0; i < SqlList.size(); ) {
                    boolean Istate = false;
                    for (int j = 0; j < userRoleIdList.size(); ) {
                        if (SqlList.get(i).toString().trim().equals(userRoleIdList.get(j).toString().trim())) {
                            Istate = true;
                            userRoleIdList.remove(j);
                        } else {
                            j++;
                        }
                    }
                    if (Istate) {
                        SqlList.remove(i);
                    } else {
                        i++;
                    }
                }
                //SqlList该删的删 userRoleIdList该增的增
                for (String each : SqlList) {
                    user_service.deleteUserRole(user_entity.getUserid(), each);
                }
                for (String item : userRoleIdList) {
                    user_service.saveUserRole(user_entity.getUserid(), item);
                }
            }
        }
        return "ClientInformation/User";
    }

    //获取当前用户所属组
    @ResponseBody
    @RequestMapping(value = "/User/getUserRoleInfoList", method = RequestMethod.GET)
    public String getUserRoleInfoList(@RequestParam String UserId) {
        Gson gson = new Gson();
        String userRoleInfoList = gson.toJson(user_service.getUserRoleInfoList(UserId));
        System.out.println(userRoleInfoList);
        return userRoleInfoList;
    }

    @ResponseBody
    @RequestMapping(value = "/User/getAllRoleInfoList", method = RequestMethod.GET)
    public String getAllRoleInfoList() {
        Gson gson = new Gson();
        String allRoleInfoList = gson.toJson(user_service.getAllRoleInfoList());
        System.out.println(allRoleInfoList);
        return allRoleInfoList;
    }

    @ResponseBody
    @RequestMapping(value = "/User/getHistoryListbyBranch", method = RequestMethod.GET)
    public String getHistoryListbyBranch(@RequestParam String branchCode, int pageSize, int pageIndex) {
        Gson gson = new Gson();
        int total = user_service.countByBranch(branchCode);
        PageHelper.startPage(pageIndex, pageSize);
        List<User_Entity> list = user_service.findByBranch(branchCode);
        String historyList = gson.toJson(list);
        String errorCode = "0";
        return "{\"rowDatas\":" + historyList + ",\"dataLength\":" + total + ",\"errCode\":" + errorCode + "}";
    }

    @ResponseBody
    @RequestMapping(value = "/User/getHistoryListbyUserId", method = RequestMethod.GET)
    public String getHistoryListbyUserId(@RequestParam String userCode, int pageSize, int pageIndex) {
        Gson gson = new Gson();
        int total = user_service.countByUserId(userCode);
        PageHelper.startPage(pageIndex, pageSize);
        List<User_Entity> list = user_service.findByUserId(userCode);
        String historyList = gson.toJson(list);
        String errorCode = "0";
        return "{\"rowDatas\":" + historyList + ",\"dataLength\":" + total + ",\"errCode\":" + errorCode + "}";
    }

    @ResponseBody
    @RequestMapping(value = "/User/getHistoryListbyUserIdandBranch", method = RequestMethod.GET)
    public String getHistoryListbyUserIdandBranch(@RequestParam String userCode, @RequestParam String branchCode, int pageSize, int pageIndex) {
        Gson gson = new Gson();
        int total = user_service.countByUserIdandBranch(userCode, branchCode);
        PageHelper.startPage(pageIndex, pageSize);
        List<User_Entity> list = user_service.findByUserIdandBranch(userCode, branchCode);
        String historyList = gson.toJson(list);
        String errorCode = "0";
        return "{\"rowDatas\":" + historyList + ",\"dataLength\":" + total + ",\"errCode\":" + errorCode + "}";
    }

    @ResponseBody
    @RequestMapping("/User/getHistoryList")
    public String getHistoryList(int pageSize, int pageIndex) {
        Gson gson = new Gson();
        int total = user_service.countAll();
        PageHelper.startPage(pageIndex, pageSize);
        List<User_Entity> list = user_service.findAll();
        String historyList = gson.toJson(list);
        String errorCode = "0";
        return "{\"rowDatas\":" + historyList + ",\"dataLength\":" + total + ",\"errCode\":" + errorCode + "}";
    }

    @ResponseBody
    @RequestMapping(value = "/User/checkUser", method = RequestMethod.GET)
    public String checkUser(@RequestParam String UserId) {
        boolean count = user_service.findOne(UserId);
        if (count)
            return "true";
        else
            return "false";
    }

    @ResponseBody
    @RequestMapping(value = "/User/deleteUser", method = RequestMethod.GET)
    public String deleteUser(@RequestParam String UserId) {
        boolean state = user_service.delete(UserId) & user_service.deleteRoleByUserId(UserId) & tbluser_properties_service.deleteOneUserProperty(UserId);
        if (state)
            return "true";
        else
            return "false";
    }


}
